/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
 var lowestCommonAncestor = function(root, p, q) {
    let res;
    function digui(root,p,q){  //左右同时找到结果的节点只有一个
       if(!root || res){
           return false;
       }
       let left=digui(root.left,p,q);
       let right=digui(root.right,p,q);
       if(left&&right || (left||right)&&(root==p||root==q)){
           res=root;
       }
       return left||right||(root==p||root==q);
    }
    digui(root,p,q);
    return res;
}
 var lowestCommonAncestor = function(root, p, q) {
    if(!root){
        return 0;
    }
    if(root==p){
        return 1;
    }
    if(root==q){
        return 1;
    }
    let left=lowestCommonAncestor(root.left),right=lowestCommonAncestor(root.right);
    if(typeof(left)!="number"){
        return left;
    }
    if(typeof(right)!="number"){
        return right;
    }
    if(left+right==2){
        return root;
    }
    return left+right;
}
 var lowestCommonAncestor = function(root, p, q) {
    let res;
    if(search(root,q)&&search(root,p)){
        res=root.val;
        res=lowestCommonAncestor(root.left,p,q)||lowestCommonAncestor(root.right,p,q)||res;
        return res;
    }
    else{
        return ;
    }
    function search(root,target){
        if(!root){
            return false;
        }
        if(root.val==target){
            return true;
        }
        return search(root.left)||search(root.right);
    }
};